package com.luoye.lj.platform.controller;

import com.luoye.lj.platform.model.UserModel;
import com.luoye.lj.platform.model.domain.SearchParams;
import com.luoye.lj.platform.model.domain.manage.ManageLog;
import com.luoye.lj.platform.model.domain.manage.ManageLogCollection;
import com.luoye.lj.platform.model.domain.manage.ManageLogSearchCondition;
import com.luoye.lj.platform.model.domain.muser.MUserDetail;
import com.luoye.lj.platform.service.IMuserservice;
import com.luoye.lj.platform.service.OperationNameGetter;
import com.luoye.lj.util.excel.DefaultReportExclUtils;
import com.luoye.lj.util.excel.ExportData;
import com.luoye.lj.util.excel.IExclUtils;
import com.luoye.lj.util.mvc.data.SimpleListResult;
import com.luoye.lj.util.mvc.util.PageService;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by wei on 2015/12/4.
 */
@Controller
@RequestMapping("/system/logger")
public class LoggerController {
    private Logger logger = LoggerFactory.getLogger(LoggerController.class);

    @Resource
    private IMuserservice muservice;

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
    }

    @RequestMapping("/list")
    public String tolist(Model model){
        OperationNameGetter operationNameGetter=new OperationNameGetter();
        List<String> operationNames= operationNameGetter.getAllOperationNames();
        logger.debug("operationNames->"+operationNames);
        model.addAttribute("operationNames",operationNames);
        model.addAttribute("title","操作日志");
        return "system/logger/logger_list";
    }

    @RequestMapping("/search")
    @ResponseBody
    public SimpleListResult searchLogger(String username, String aurl, String operatename, String description,
                                         String aip, String beginTime, String endTime,
                                         @RequestParam(value = "page", defaultValue = "1")int page,
                                         @RequestParam(value = "max", defaultValue = "10")int max){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm");
        ManageLogSearchCondition searchCondition = new ManageLogSearchCondition();
        if(!StringUtils.isEmpty(beginTime)){
            try {
                Date btime = sdf.parse(beginTime);
                searchCondition.setBeginTime(btime);
                sdf.format(btime);
            }catch(ParseException e){
            }
        }

        if(!StringUtils.isEmpty(endTime)){
            try {
                Date etime = sdf.parse(endTime);
                searchCondition.setEndTime(etime);
                sdf.format(etime);
            }catch(ParseException e){
            }
        }
        int offset = (page - 1) * max;
        logger.debug("offset->" + offset + ",max->" + max);
        SearchParams searchParams = new SearchParams();
        searchParams.setOffset(offset);
        searchParams.setMax(max);
        searchCondition.setSearchParams(searchParams);

        searchCondition.setDescription(description);
        searchCondition.setAip(aip);
        searchCondition.setAurl(aurl);
        searchCondition.setOperatename(operatename);
        searchCondition.setUsername(username);

        ManageLogCollection collection = null;
        try {
            collection = muservice.searchManageLog(searchCondition);
        }catch(Exception e){
            ManagerController.logger.error(e.getMessage());
            logger.warn(e.getMessage(),e);
        }
        SimpleListResult slr = new SimpleListResult();
        slr.setRows(collection.getManageLogList());
        slr.setCurrentPage(page);
        slr.setResults(collection.getTotalCount());
        slr.setPages(PageService.countPages(max, slr.getResults()));
        return slr;
    }

    @RequestMapping("/to_my_log")
    public String toMyLog(Model model) {
        model.addAttribute("title","我的操作日志");
        return "system/logger/my_logger_list";
    }

    @RequestMapping("/search_mylog")
    @ResponseBody
    public SimpleListResult searchLogger(String description,
                                         String beginTime,
                                         String endTime,
                                         @RequestParam(value = "page", defaultValue = "1")int page,
                                         @RequestParam(value = "max", defaultValue = "10")int max){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm");
        ManageLogSearchCondition searchCondition = new ManageLogSearchCondition();
        if(!StringUtils.isEmpty(beginTime)){
            try {
                Date btime = sdf.parse(beginTime);
                searchCondition.setBeginTime(btime);
                sdf.format(btime);
            }catch(ParseException e){
            }
        }

        if(!StringUtils.isEmpty(endTime)){
            try {
                Date etime = sdf.parse(endTime);
                searchCondition.setEndTime(etime);
                sdf.format(etime);
            }catch(ParseException e){
            }
        }

        String username = null;
        if (SecurityContextHolder.getContext().getAuthentication().getPrincipal() instanceof UserModel) {
            UserModel userDetails = (UserModel) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            MUserDetail mUserDetail = userDetails.getmUserDetail();
            username = mUserDetail.getUsername();
        } else {
            username="null";
        }
        searchCondition.setDescription(description);
        searchCondition.setUsername(username);

        int offset = (page - 1) * max;
        logger.debug("offset->" + offset + ",max->" + max);
        SearchParams searchParams = new SearchParams();
        searchParams.setOffset(offset);
        searchParams.setMax(max);
        searchCondition.setSearchParams(searchParams);
        ManageLogCollection collection = null;
        try {
            collection = muservice.searchManageLog(searchCondition);
        }catch(Exception e){
            ManagerController.logger.error(e.getMessage());
            logger.warn(e.getMessage(),e);
        }
        SimpleListResult slr = new SimpleListResult();
        slr.setRows(collection.getManageLogList());
        slr.setCurrentPage(page);
        slr.setResults(collection.getTotalCount());
        slr.setPages(PageService.countPages(max, slr.getResults()));
        return slr;
    }

    @RequestMapping("/exportExcel")
    public void exportExcel(HttpServletRequest request, HttpServletResponse response,
                            String username, String aurl, String operatename, String description,
                            String aip, String beginTime, String endTime){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm");
        ManageLogSearchCondition searchCondition = new ManageLogSearchCondition();
        if(!StringUtils.isEmpty(beginTime)){
            try {
                Date btime = sdf.parse(beginTime);
                searchCondition.setBeginTime(btime);
                sdf.format(btime);
            }catch(ParseException e){
            }
        }

        if(!StringUtils.isEmpty(endTime)){
            try {
                Date etime = sdf.parse(endTime);
                searchCondition.setEndTime(etime);
                sdf.format(etime);
            }catch(ParseException e){
            }
        }
        SearchParams searchParams = new SearchParams();
        searchCondition.setSearchParams(searchParams);
        searchCondition.setDescription(description);
        searchCondition.setAip(aip);
        searchCondition.setAurl(aurl);
        searchCondition.setOperatename(operatename);
        searchCondition.setUsername(username);
        logger.debug("searchCondition->"+searchCondition);
        try {
            request.setCharacterEncoding("utf-8");
            response.setCharacterEncoding("utf-8");

        } catch (UnsupportedEncodingException e) {
        }
        String filename = "";
        try {
            filename = URLEncoder.encode("操作日志报表.xlsx", "UTF-8");
        } catch (UnsupportedEncodingException e) {
        }
        response.setHeader("content-disposition", "attachment;filename="+filename);
        response.setContentType("application/octet-stream");
        List<String[]> showFieldList=new ArrayList<>();
        showFieldList.add(new String[]{"id","编号"});
        showFieldList.add(new String[]{"userid","用户编号"});
        showFieldList.add(new String[]{"username","用户名"});
        showFieldList.add(new String[]{"aurl","请求URL"});
        showFieldList.add(new String[]{"aparams","请求参数"});
        showFieldList.add(new String[]{"atime","操作时间"});
        showFieldList.add(new String[]{"operatename","操作名称"});
        showFieldList.add(new String[]{"description","操作描述"});
        showFieldList.add(new String[]{"aip","访问IP"});
        showFieldList.add(new String[]{"browser","浏览器"});
        IExclUtils reportExclUtils = new DefaultReportExclUtils<ManageLog>(showFieldList,"操作日志");
        SXSSFWorkbook wb = new SXSSFWorkbook(100);
        ExportData exportData = new ExportData();
        exportData.setFromN(1);
        exportData.setBegin(0);
        //写入头
        exportData = reportExclUtils.createHead(null, wb, exportData);

        //每次最多查20000条,并写入明细
        searchCondition.getSearchParams().setOffset(0);
        searchCondition.getSearchParams().setMax(20000);
        logger.info("searchCondition->" + searchCondition);
        int offset=0;
        int totalCount=-1;
        while (totalCount==-1||totalCount>offset) {//循环查询
            searchCondition.getSearchParams().setOffset(offset);
            ManageLogCollection collection = muservice.searchManageLog(searchCondition);
            totalCount=collection.getTotalCount();
            exportData = reportExclUtils.createSheet(collection.getManageLogList(), wb, exportData);
            offset+=searchCondition.getSearchParams().getMax();
        }

        //写入尾
//        HashMap<String,TestDbo> dataMap=new HashMap<>();
//        TestDbo testDbo = testService.statisticsByCondition(testDboSearchCondition);
//        dataMap.put("reportStatistics",testDbo);
//        exportData = reportExclUtils.createTail(dataMap, wb, exportData);

        try {
            wb.write(response.getOutputStream());
        } catch (IOException e) {
            logger.warn(e.getMessage(),e);
        }
    }
}
